package com.netty.pro.netty.protobuf2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

/**
 * @author xuzn
 * @ClassName: NettyClient
 * @ProjectName netty-pro
 * @date 2020/3/10/17:24
 */
public class ProtoBufNettyClient2 {
  public static void main(String[] args) throws Exception {
    // 客户端需要一个事件循环组
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    // 客户端使用的不是ServerBootStrap而是Bootstrap
    Bootstrap bootstrap = new Bootstrap();
    try {
      // 设置线程组
      bootstrap.group(eventLoopGroup)
              // 设置客户端通道实现类(通过反射实现)
              .channel(NioSocketChannel.class)
              // 创建初始对象
              .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline pipeline = ch.pipeline();
                  pipeline.addLast("protobufEncoder", new ProtobufEncoder());
                  // 加入自己的处理器
                  pipeline.addLast(new ProtobufNettyClientHandler());
                }
              });
      // 服务端链接服务器
      ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7000).sync();
      channelFuture.channel().closeFuture().sync();
    } finally {
      eventLoopGroup.shutdownGracefully();
    }
  }
}
